const request = require("request")
const url = require("url")

module.exports = (opts) => {
    if (opts.method === "GET") {
        opts.url += url.format({ query: opts.body });
        delete opts.body;
    } else if (opts.method === "POST") {
      opts.json = true;  // https://github.com/request/request-promise/issues/215
    }
    return new Promise((resolve, reject) => {
        request(opts, (err, res, body) => {
            if (err || res.statusCode != 200) {
                reject(err || body);
            }
            else {
                if (typeof (body) == 'string') {
                    try {
                        body = JSON.parse(body);
                    }
                    catch (e) {
                        reject(e);
                    }
                }
                resolve(body);
            }
        });
    });
}
